package com.largeOrange.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.largeOrange.dto.DishDto;
import com.largeOrange.mapper.DishMapper;
import com.largeOrange.pojo.Dish;
import com.largeOrange.pojo.DishFlavor;
import com.largeOrange.service.DishFlavorService;
import com.largeOrange.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 大橙子
 * @version 1.0
 * @since 1.0
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    DishFlavorService dishFlavorService;
    /**
     * 将数据保存在两张表中
     * @param dto
     */
    @Override
    @Transactional
    public void saveDishAndFlavor(DishDto dto) {
        this.save(dto);
        //获取第一张表id
        Long dishId = dto.getId();
        //获取口味数据
        List<DishFlavor> flavors = dto.getFlavors();
        //将数据存放至dish_flavor表中
        flavors.forEach(flavor->{
            flavor.setDishId(dishId);
            dishFlavorService.save(flavor);
        });
    }

    @Override
    public DishDto dishFlavorAppear(Long id) {
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(id!=null,DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        dishDto.setFlavors(list);
        dishDto.setCategoryName(dish.getName());
        return dishDto;
    }
    @Transactional
    @Override
    public void updateDishAndFlavor(DishDto dishDto) {
        Long dishDtoId = dishDto.getId();
        //移除dish表中的相应数据
        this.removeById(dishDtoId);
        //移除dishFlavor表中的相应数据
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dishDtoId);
        dishFlavorService.remove(wrapper);
        //重新保存数据
        this.saveDishAndFlavor(dishDto);
    }
    @Transactional
    @Override
    public void deleteDishAndFlavor(Long[] dishId) {
        for (Long id : dishId) {
            this.removeById(id);
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
            dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        }
    }
}
